import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lib_uikit/resource/resources.dart';
import 'package:lib_uikit/widgets/dropdown/gt_dropdown_stroke_widget_v3.dart';
import 'package:lib_uikit/widgets/dropdown/gt_dropdown_text_widget_v3.dart';
import 'package:lib_uikit/widgets/dropdown/gt_dropdown_top_popup_v3.dart';
import 'package:lib_uikit/widgets/gt_search_view_v3.dart';

///Large size24; Medium size20; Small size16; XSmall size14
enum GTDropdownSizeV3 { size24, size20, size16, size15, size14 }

///Large size44; Medium size40; Small size30; XSmall size24
enum GTStrokeDropdownSizeV3 { size44, size40, size30, size24 }

enum GTDropdownTypeV3 { text, stroke }

class GTDropdownV3 extends StatefulWidget {
  final GTDropdownSizeV3? size;
  String text;
  final Color? textColor;
  final String? imagePath;
  final double? paddingHorizontal;
  final double? paddingVertical;
  final String? popupTitle;
  final List<GTDropDownContentModalV3>? list;
  final bool? showInput;
  final String? inputHint;
  final bool? showStroke;
  final Color? popupSelectBackground;
  final ValueChanged<GTDropDownContentModalV3>? onItemClicked;
  final ValueChanged<String>? onSearchSubmit;
  final bool? linearArrow; //线性箭头

  //不弹底部弹窗，需要自己处理点击事件
  final VoidCallback? onPressed;
  final bool? showPopup;

  //处理箭头样式
  final bool? arrowUp;

  //弹窗空数据文案
  final String? emptyText;

  //固定最小高度比例，修复搜索过滤数据后高度改编的问题
  final double? minHeightPercent;

  //默认选中下标
  final int? defaultSelectIndex;

  //点击弹窗外部是否可收起弹窗，默认true可收起
  final bool? isDismissible;

  //修复软键盘把弹窗顶起问题
  final bool? autoResize;
  final bool? transparentBackground;
  final GTDropdownTypeV3? type;

  //仅限输入框组件使用
  final bool? textFieldType;

  ///strokeType属性：
  final GTStrokeDropdownSizeV3? strokeSize;
  final Widget? startWidget;
  final String? endText;
  final bool? fullWidth;
  final IconData? startIcon;
  final bool? isEnabled;
  final String? title;
  final String? bottomText;

  ///从顶部展示的弹窗
  final bool? isTopExpand;

  ///从顶部弹出的popup最大比例高度，默认0.8
  final double? topPopupMaxPercentHeight;

  ///smartDialog show/dismiss的 tag
  final String? tag;

  ///stroke样式-展示Title红色星号
  final bool? showTitleMarket;

  ///标题左边币种图片URL
  final String? titleCoinUrl;

  GTDropdownV3({
    super.key,
    this.size = GTDropdownSizeV3.size24,
    this.text = "",
    this.textColor,
    this.imagePath,
    this.paddingVertical,
    this.paddingHorizontal,
    this.popupTitle,
    this.list,
    this.showInput,
    this.inputHint,
    this.showStroke,
    this.popupSelectBackground,
    this.onItemClicked,
    this.onSearchSubmit,
    this.linearArrow = false,
    this.showPopup = true,
    this.onPressed,
    this.emptyText,
    this.minHeightPercent,
    this.defaultSelectIndex,
    this.isDismissible,
    this.autoResize = true,
    this.transparentBackground = true,
    this.textFieldType,
    this.type,
    this.strokeSize,
    this.startWidget,
    this.endText,
    this.arrowUp,
    this.fullWidth,
    this.startIcon,
    this.isEnabled,
    this.title,
    this.bottomText,
    this.isTopExpand,
    this.topPopupMaxPercentHeight = 0.8,
    this.tag,
    this.showTitleMarket,
    this.titleCoinUrl,
  });

  @override
  State<StatefulWidget> createState() => _DropdownStateV3();
}

class _DropdownStateV3 extends State<GTDropdownV3> {
  //点击列表title
  String _title = "";
  bool isFirst = true;
  bool _popupShowing = false;
  List<GTDropDownContentModalV3> _filteredList = [];
  String _searchText = "";
  double space = 4;
  GTDropdownTypeV3 dropdownType = GTDropdownTypeV3.text;

  @override
  void initState() {
    dropdownType = widget.type ?? GTDropdownTypeV3.text;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Color _popupSelectBackground = widget.popupSelectBackground ?? GTColorsV3.neutral2.color;
    bool _showPopup = widget.showPopup ?? true;
    //屏幕高度
    double screenHeight = MediaQuery.of(context).size.height;

    Widget child = StatefulBuilder(builder: (context, setState) {
      return ConstrainedBox(
        constraints: BoxConstraints(
          minHeight: screenHeight * (widget.minHeightPercent ?? 0.5),
        ),
        child: Container(
          decoration: BoxDecoration(
            color: GTColorsV3.cmpt16.color,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(12),
              topRight: Radius.circular(12),
            ),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    margin: const EdgeInsets.symmetric(vertical: 16),
                    child: Text(
                      widget.popupTitle ?? "",
                      style: gtTextStyleW600(fontSize: 16, color: GTColorsV3.text1.color),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      child: Icon(
                        GTIconFont.e89b,
                        size: 16,
                        color: GTColorsV3.icon3.color,
                      ),
                    ),
                  ),
                ],
              ),
              if (widget.showInput ?? false) ...[
                const SizedBox(
                  height: 8,
                ),
                GTSearchViewV3(
                  hint: widget.inputHint ?? "",
                  type: GTSearchTypeV3.dropdown,
                  onSubmit: (String value) {
                    if (value.isNotEmpty) {
                      widget.onSearchSubmit?.call(value);
                    }
                    WidgetsBinding.instance.addPostFrameCallback((_) {
                      SystemChannels.textInput.invokeMethod('TextInput.hide');
                    });
                  },
                  onTextChanged: (text) {
                    setState(() {
                      _searchText = text;
                      _filteredList = (widget.list ?? [])
                          .where((item) => item.title.toLowerCase().contains(text.toLowerCase()))
                          .toList();
                    });
                  },
                ),
                const SizedBox(
                  height: 8,
                )
              ],
              Flexible(
                flex: 1,
                child: _filteredList.isEmpty
                    ? const Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            height: 50,
                          ),
                          GTEmptyViewV3(
                            iconType: GTEmptyIconType.search,
                          )
                        ],
                      )
                    : ListView.separated(
                        itemCount: _filteredList.length,
                        shrinkWrap: true,
                        physics: const ClampingScrollPhysics(),
                        separatorBuilder: (context, index) => const SizedBox(height: 8),
                        itemBuilder: (context, index) {
                          final title = _filteredList[index].title;
                          final searchTextIndex =
                              _searchText.isEmpty ? -1 : title.toLowerCase().indexOf(_searchText.toLowerCase());
                          return GestureDetector(
                            onTap: () {
                              Navigator.pop(context);
                              setState(() {
                                _title = _filteredList[index].title;
                                isFirst = false;
                              });
                              widget.onItemClicked?.call(_filteredList[index]);
                            },
                            child: Container(
                                decoration: BoxDecoration(
                                  color: _title == _filteredList[index].title
                                      ? _popupSelectBackground
                                      : Colors.transparent,
                                  borderRadius: BorderRadius.circular(6),
                                ),
                                height: 44,
                                child: Row(children: <Widget>[
                                  const SizedBox(width: 12),
                                  if (_filteredList[index].imagePath != null) ...[
                                    GTImage(
                                      url: _filteredList[index].imagePath ?? "",
                                      width: 24,
                                      height: 24,
                                      radiusAll: 12,
                                      showPlaceholder: true,
                                      fit: BoxFit.cover,
                                      errorPath: Images.uikitPlaceholder,
                                      placeholderPath: Images.uikitPlaceholder,
                                    ),
                                    const SizedBox(width: 8),
                                  ],
                                  Expanded(
                                    child: searchTextIndex == -1
                                        ? Text(
                                            title,
                                            style: gtTextStyleW500(color: GTColorsV3.text1.color, fontSize: 16),
                                          )
                                        : Text.rich(
                                            TextSpan(
                                              children: [
                                                TextSpan(
                                                  text: title.substring(0, searchTextIndex),
                                                ),
                                                TextSpan(
                                                  text: title.substring(
                                                      searchTextIndex, searchTextIndex + _searchText.length),
                                                  style: gtTextStyleW500(color: GTColorsV3.brand3.color, fontSize: 16),
                                                ),
                                                TextSpan(
                                                  text: title.substring(searchTextIndex + _searchText.length),
                                                ),
                                              ],
                                              style: gtTextStyleW500(color: GTColorsV3.text1.color, fontSize: 16),
                                            ),
                                          ),
                                  ),
                                  if (_filteredList[index].endText != null)
                                    Text(
                                      _filteredList[index].endText ?? "",
                                      style: gtTextStyleW500(color: GTColorsV3.text1.color, fontSize: 14),
                                    ),
                                  const SizedBox(
                                    width: 16,
                                  ),
                                  if (_title == _filteredList[index].title) ...[
                                    Icon(
                                      GTIconFont.e942,
                                      color: GTColorsV3.icon9.color,
                                      size: 16,
                                    ),
                                    const SizedBox(width: 12),
                                  ],
                                ])),
                          );
                        },
                      ),
              ),
            ],
          ),
        ),
      );
    });

    child = GestureDetector(
      onTap: () => Navigator.pop(context),
      child: Column(
        children: [
          Container(
            height: screenHeight * 0.2,
            color: Colors.transparent,
          ),
          Expanded(
            child: Container(
              color: Colors.transparent,
              child: Align(
                alignment: Alignment.bottomCenter,
                child: GestureDetector(
                  onTap: () {},
                  child: child,
                ),
              ),
            ),
          )
        ],
      ),
    );

    Widget _dropdownView() {
      return dropdownType == GTDropdownTypeV3.text
          ? GTTextDropdownWidgetV3(
              text: widget.text,
              textColor: widget.textColor,
              popupShowing: widget.arrowUp ?? _popupShowing,
              paddingHorizontal: widget.paddingHorizontal,
              paddingVertical: widget.paddingVertical,
              showStroke: widget.showStroke,
              imagePath: widget.imagePath,
              size: widget.size,
              linearArrow: widget.linearArrow,
            )
          : GTStrokeDropdownWidgetV3(
              text: widget.text,
              textColor: widget.textColor,
              size: widget.strokeSize,
              startWidget: widget.startWidget,
              endText: widget.endText,
              popupShowing: widget.arrowUp ?? _popupShowing,
              fullWidth: widget.fullWidth,
              startIcon: widget.startIcon,
              isEnabled: widget.isEnabled,
              title: widget.title,
              bottomText: widget.bottomText,
              showTitleMarket: widget.showTitleMarket,
              titleCoinUrl: widget.titleCoinUrl,
            );
    }

    if (widget.isTopExpand ?? false) {
      if (widget.defaultSelectIndex != null && widget.list != null) {
        _title = widget.list![(widget.defaultSelectIndex ?? 0)].title;
      }
      return GTDropdownTopPopupV3(
        child: _dropdownView(),
        showInput: widget.showInput,
        list: widget.list,
        selectTitle: _title,
        onPressed: widget.onPressed,
        topPopupMaxPercentHeight: widget.topPopupMaxPercentHeight,
        text: widget.text,
        textColor: widget.textColor,
        tag: widget.tag,
        onDropdownPressed: (popupShowing) {
          setState(() {
            _popupShowing = popupShowing;
          });
        },
        onItemClicked: (bean) {
          setState(() {
            _title = bean.title;
            _popupShowing = false;
          });
          widget.onItemClicked?.call(bean);
        },
      );
    }

    return GestureDetector(
        onTap: () {
          widget.onPressed?.call();
          if (!_showPopup) {
            return;
          }
          bool needDismissKeyboard = true;
          if (FocusManager.instance.primaryFocus?.hasFocus ?? false) {
            needDismissKeyboard = true;
            FocusManager.instance.primaryFocus?.unfocus();
          }
          setState(() {
            _popupShowing = true;
          });

          _filteredList = widget.list ?? [];
          _searchText = '';
          if (_filteredList.isNotEmpty && isFirst) _title = _filteredList[widget.defaultSelectIndex ?? 0].title;
          Future.delayed(Duration(milliseconds: needDismissKeyboard ? 100 : 0), () {
            showModalBottomSheet(
              //解决弹窗设置圆角后会漏出底部背景色问题
              backgroundColor: Colors.transparent,
              context: context,
              isScrollControlled: true,
              isDismissible: widget.isDismissible ?? true,
              builder: (BuildContext context) {
                if (widget.autoResize ?? true) {
                  return AnimatedPadding(
                    padding: MediaQuery.of(context).viewInsets,
                    duration: const Duration(milliseconds: 100),
                    child: child,
                  );
                } else {
                  return child;
                }
              },
            ).then((value) {
              //弹窗关闭回调
              setState(() {
                _popupShowing = false;
              });
            });
          });
        },
        child: _dropdownView());
  }
}

class GTDropDownContentModalV3 {
  final String? imagePath;
  final String title;
  final String? endText;

  GTDropDownContentModalV3({this.imagePath, required this.title, this.endText});
}
